﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace E0XPayService.Utils
{
    public class DBHelper
    {
        /// <summary>
        /// 执行存储过程获取返回数据
        /// </summary>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DataTable GetTableFromSP(string storedProcName, IDataParameter[] parameters)
        {
            string connectionString = CEncrypt.DecryString(ConfigurationManager.ConnectionStrings["ConnectString"].ToString());
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataTable table = new DataTable();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                SqlCommand command = new SqlCommand(storedProcName, connection);
                command.CommandType = CommandType.StoredProcedure;//类型为存储过程
                if (parameters != null)//检查过程参数
                {
                    foreach (SqlParameter parameter in parameters)
                    {
                        command.Parameters.Add(parameter);
                    }
                }
                sqlDA.SelectCommand = command;
                SqlDataReader sdr = command.ExecuteReader();//执行过程
                table.Load(sdr);
                connection.Close();
                
                return table;
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        public static void ExecuteNonQuerySP(string storedProcName, IDataParameter[] parameters)
        {
            string connectionString = CEncrypt.DecryString(ConfigurationManager.ConnectionStrings["ConnectString"].ToString());
            using (SqlConnection connection = new SqlConnection(connectionString))
            {               
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                SqlCommand command = new SqlCommand(storedProcName, connection);
                command.CommandType = CommandType.StoredProcedure;//类型为存储过程
                if (parameters != null)//检查过程参数
                {
                    foreach (SqlParameter parameter in parameters)
                    {
                        command.Parameters.Add(parameter);
                    }
                }
                sqlDA.SelectCommand = command;
                command.ExecuteNonQuery();//执行过程
                connection.Close();
            }
        }
    }
}